<?php
/**
 * Peizhi 插件
 * @author 后盾向军 <houdunwangxj@gmail.com>
 */
class PeizhiAddon extends Addon
{

    //插件信息
    public $info = array(
        'name' => 'Peizhi',
        'title' => '配置开关',
        'description' => '网站开关配置',
        'status' => 1,
        'author' => 'long',
        'version' => '1.0',
        'has_adminlist' => 1,
    );

    //安装
    public function install()
    {
        if (!M()->exe("DROP TABLE IF EXISTS `" . C('DB_PREFIX') . "peizhi`")) return false;
        if (!M()->exe("CREATE TABLE `" . C('DB_PREFIX') . "peizhi` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'peizhi',
  `name` varchar(50) DEFAULT NULL COMMENT 'name',
  `value` int(10) unsigned DEFAULT NULL COMMENT '值',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='配置信息表'")
        ) return false;
            M()->exe("INSERT INTO `" . C('DB_PREFIX') . "peizhi` SET name='tiao',value='1'" );
            M()->exe("INSERT INTO `" . C('DB_PREFIX') . "peizhi` SET name='ip',value='1'" );
            M()->exe("INSERT INTO `" . C('DB_PREFIX') . "peizhi` SET name='address',value='1'" );
            M()->exe("INSERT INTO `" . C('DB_PREFIX') . "peizhi` SET name='black',value='5'" );
        return true;
    }

    //卸载
    public function uninstall()
    {
        if (!M()->exe("DROP TABLE IF EXISTS `" . C('DB_PREFIX') . "peizhi`")) return false;
        return true;
    }

    /**
     * 获取当前ip
     * @return [type] [description]
     */
    protected function getIpAddress(){
        return ip_get_client();
    }
    protected function getIpBlack(){
        $ip = M('ip')->all();
        return $ip;
    }

    protected function getBlockAddress(){
        $addblack = M('address')->all();
        $add=array();
       foreach ($addblack as $key => $value) {
           $add['sheng'][]=$value['sheng'];
           $add['city'][]=$value['city'];

       }

       return $add;
    }

    /**
     * 获取ip所在地址
     * @return [type] [description]
     */
    protected function getAddress(){
        $ip=$this->getIpAddress();
        $address=file_get_contents("http://api.map.baidu.com/location/ip?ak=IhXGS5bx8SyQ0NWAT1REwjya&ip=".$ip);
        $address = json_decode($address,true);
        $info = array();
        if($address['status']!=0){
            $info['sheng']='未知';
            $info['city']='未知';
        }else{
            $info['sheng']=$address['content']['address_detail']['province'];
            $info['city']=$address['content']['address_detail']['city'];
            
        }
        return $info;
    }

    protected function getBrowser(){
        return browser_info();
    }
    /**
     * 获取配置信息
     * @return [type] 配置
     */
    protected function getPeizhi(){

        $config=M('peizhi')->all();

        $peizhi = array();
        foreach ($config as $key => $value) 
        {
            $peizhi[$value['name']]=$value['value'];
        }
        return $peizhi;
    }

    /**
     * 获取域名绑定信息
     * @return [type] [description]
     */
    protected function getBangding(){
        $bangding = M('bangding')->where(array('domain'=>$_SERVER['HTTP_HOST']))->find();
        if(!$bangding)
        {
            return false;
        }else{
            return $bangding;
        }
    }

    protected function getTongji($ip){
        $ipis = M('tongji')->where(array('ip'=>$ip))->find();
        if($ipis)
        {
            return $ipis;
        }else{
            return false;
        }
    }
    protected function check(){

        $ip=$this->getIpAddress();
        $address = $this->getAddress();
        $addblack = $this->getBlockAddress();
        $peizhi = $this->getPeizhi();
        $referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :'直接访问';
        $domain = $_SERVER['HTTP_HOST'];

        // 组装ip段
        $ip1 = explode('.', $ip);
        $ip1 = $ip1[0].'.'.$ip1[1].'.'.$ip1[2];
        $where['ip'] = array('like',"$ip1%");
        $where['type'] = "C";
        $where['_logic'] = "AND";
        // 根据三位ip查c类
        $cip = M('ip')->where($where)->select();

        $map=array('ip'=>$ip,'type'=>"D");
        // 根据四位ip查d类
        $dip = M('ip')->where($map)->select();

        if($cip||$dip)
        {
            $s = 1;
        }else{
            $s = 0;
        }

        $browser = $this->getBrowser();
        if(ismobile())
        {
            $browser = "*".$browser;
        }
        $ipinfo = array(
              'ip' => $ip,
              'domain' => $domain,
              'sheng' => $address['sheng'],
              'city' => $address['city'],
              'referer'=>$referer,
              'browser' => $browser,
              'time' => time(),
              'click' => 1,
              'status' => $s
                );
        // 统计列表里的次数
        $tongji = $this->getTongji($ip);

        if(!$tongji)
        {   
        // 统计列表添加一条记录
            M('tongji')->data($ipinfo)->add();
        }else{
            // 如果点击次数等于拉黑限制

            $ipinfo['click'] = $tongji['click']+1;
            unset($ipinfo['ip']);
            // 更新统计列表里的点击次数
            M('tongji')->data($ipinfo)->where(array('ip'=>$ip))->save();

            if($tongji['click']>=$peizhi['black'])
            {
                $info['status'] = false;
                $info['msg'] = "{$ip}访问次数超过限制";
                return $info;
            }
        }

         // 判断ip是否在黑名单   
        if($cip||$dip)
        {   
            
            $info['status'] = false;
            $info['msg'] = "{$ip}黑名单ip";
            return $info;
        }    

        // 判断全局开关是否开启
        
        if($peizhi['tiao']==0)
        {
            $info['status'] = false;
            $info['msg'] = "{$ip}全站配置关闭跳转";
            return $info;
        }

        if(in_array($address['sheng'], $addblack['sheng']))
        {
            $info['status'] = false;
            $info['msg'] = "{$ip}省份屏蔽";
            return $info;
        }
        if(in_array($address['city'], $addblack['city']))
            {
                $info['status'] = false;
                $info['msg'] = "{$ip}城市屏蔽";
                return $info;
            }
        // if($address['city']=="未知")
        //     {
        //         $info['status'] = false;
        //         $info['msg'] = "{$ip}未知城市";
        //         return $info;
        //     }    

        $bangding = $this->getBangding();
        if(!$bangding)
        {
            $info['status'] = false;
            $info['msg'] = "";
            return $info;
        }
            
        $info['status'] = true;
        $info['msg'] = "{$ip}访问正常";
        $ipinfo['browser'] = $ipinfo['browser'].'+';
        M('tongji')->data($ipinfo)->where(array('ip'=>$ip))->save();
        return $info;

    }


    //实现的APP_BEGIN钩子方法
    public function APP_BEGIN($param){



       if(MODULE=='Index'){

            $info = $this->check();

            if($info['status']==false)
            {
                cookie('mima',"360");
                // echo $info['msg'];
            }else{
                cookie('mima','baidu');
                // echo $info['msg'];
            }
       }
        

    }
}


